export const generateId = function () {
  return Math.floor(Math.random() * 100000 + Math.random() * 20000 + Math.random() * 5000)
}

// 树结构查找函数 - 递归实现
export function findTreeNode(tree: WidgetConfig[], targetId: string, idKey = 'id') {
  if (!Array.isArray(tree) || tree.length === 0) {
    return null
  }

  for (const node of tree) {
    if (node[idKey] === targetId) {
      return node
    }

    // 如果有子节点，递归查找
    if (node.subWidgets && Array.isArray(node.subWidgets) && node.subWidgets.length > 0) {
      const found: any = findTreeNode(node.subWidgets, targetId, idKey)
      if (found) {
        return found
      }
    }
  }

  return null
}

/**
 * 将后端返回的JSON Schema转换为特定格式的配置对象
 * @param schema - 后端返回的JSON Schema对象
 * @returns 转换后的配置对象数组
 */
export function transformSchemaToConfig(schema: any): any[] {
  // 基础配置模板
  const baseConfig: WidgetConfig = {
    icon: 'Edit',
    text: 'Opro表格',
    name: 'OproTable',
    props: {
      modelLabel: '模块名称',
      modelName: 'model-name',
      listApi: '',
      detailApi: '',
      delApi: '',
      addApi: '',
      editApi: '',
      apiPath: '',
      exportApi: '',
    },
    category: 'container',
    subWidgets: [],
    id: 'OproTable-108720',
  }

  // 检查schema是否有效
  if (
    !schema ||
    !schema.properties ||
    !schema.properties.data ||
    !schema.properties.data.properties
  ) {
    console.error('Invalid schema structure:', schema)
    return []
  }

  // 获取数据对象的属性
  const dataProperties = schema.properties.data.properties as Schema

  // 遍历数据属性并创建子组件
  for (const [fieldName, fieldSchema] of Object.entries(dataProperties)) {
    // 排除不需要的字段
    if (['id', 'code', 'msg'].includes(fieldName)) {
      continue
    }

    // 生成唯一ID
    const widgetId = `OproField-${Math.floor(Math.random() * 100000)}`

    // 确定字段类型
    let fieldType = 'input'
    if (['mcDataType', 'mcDataFlag'].includes(fieldName)) {
      fieldType = 'select'
    }

    // 确定是否可搜索
    const canSearch = ['mcCode', 'mcName', 'oproCode', 'oproName'].includes(fieldName)

    // 创建子组件配置

    baseConfig.subWidgets.push({
      icon: 'Edit',
      text: '输入框',
      name: 'OproField',
      props: {
        fieldLabel: fieldSchema.description || fieldName,
        fieldName,
        checked: true,
        canSearch,
        fieldType,
        charLength: 50,
      },
      category: 'filed',
      id: widgetId,
    })
  }

  return [baseConfig]
}
